package com.ailanyin.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ailanyin.common.constant.Constants;

import java.nio.charset.Charset;

/**
 * 获取IP工具类
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/2 0003 下午 14:10
 */
public class IpUtil {

    private final static String UNKNOWN = "unknown";
    private final static String CHINESE_UNKNOWN = "未知";
    private final static String LOCALHOST = "127.0.0.1";
    private static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";


    /**
     * 获取公网ip的实际位置
     *
     * @param ip 公网ip
     * @return eg:安徽省合肥市 电信
     */
    public static String getRealAddressByIp(String ip) {
        // 内网不查询
        if (LOCALHOST.equals(ip)) {
            return "内网IP";
        }
        try {
            String rspStr = cn.hutool.http.HttpUtil.get(IP_URL + "?ip=" + ip + "&json=true", Charset.forName(Constants.GBK));
            if (StrUtil.isEmpty(rspStr)) {
                return UNKNOWN;
            }

            return JSONUtil.parseObj(JSONUtil.toJsonStr(rspStr)).getStr("addr");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CHINESE_UNKNOWN;
    }
}
